package ua.kiev.tosik.price.modules.clients.database.prices;

import org.apache.commons.lang.time.DurationFormatUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesDao;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Prices;
import ua.kiev.tosik.price.models.PricesFiles;

import javax.swing.*;
import java.sql.SQLException;
import java.util.List;

public class PricesSaveWorker extends SwingWorker<Integer, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.prices");
	private PricesFiles pricesFiles;
	private List<Prices> pricesList;
	private IPricesDao pricesDao;
	private IPricesFilesDao pricesFilesDao;
	private long startTime = System.currentTimeMillis();

	public PricesSaveWorker() {
		super();
		logger.debug("Initialize PricesSaveWorker");
		try {
			pricesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesDao();
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public void setPricesList(List<Prices> pricesList) {
		this.pricesList = pricesList;
	}

	public void setPricesFiles(PricesFiles pricesFiles) {
		this.pricesFiles = pricesFiles;
	}

	@Override
	protected Integer doInBackground() throws Exception {
		if ( pricesDao == null ) {
			logger.error("Dao [PricesDao] is not initialized!");
			throw new Exception("Dao [PricesDao] is not initialized!");
		}
		if ( pricesFilesDao == null ) {
			logger.error("Dao [PricesFilesDao] is not initialized!");
			throw new Exception("Dao [PricesFilesDao] is not initialized!");
		}
		if ( pricesFiles == null ) {
			logger.error("PricesFiles is not defined!");
			throw new Exception("PricesFiles is not defined!");
		}
		if ( pricesList == null || pricesList.size() == 0 ) {
			logger.error("Nothing to save");
			throw new Exception("Nothing to save");
		}
		firePropertyChange("SAVE_START", false, true);
		int savedRecords = 0;
		pricesDao.getConn().setAutoCommit(false);
		// File tmpFile = new File("C:/TEMP/data.cvs");
		// StrBuilder sb = new StrBuilder();
		for (int i = 0, pricesListSize = pricesList.size(); i < pricesListSize; i++) {
			Prices prices = pricesList.get(i);
			pricesDao.save(prices);
			firePropertyChange("SAVE_RECORD_COUNT", 0, i);
			savedRecords++;

			/*
			sb.append(prices.getClientsId()); sb.append(",");
			sb.append(prices.getPricesFilesId()); sb.append(",");
			sb.append(StringEscapeUtils.escapeCsv(prices.getArticleInternal())); sb.append(",");
			sb.append(StringEscapeUtils.escapeCsv(prices.getArticle())); sb.append(",");
			sb.append(StringEscapeUtils.escapeCsv(prices.getName())); sb.append(",");
			sb.append(prices.getPrice()); sb.append(",");
			sb.append(StringEscapeUtils.escapeCsv(prices.getPricesDate().toString())); sb.append(",");
			sb.append(StringEscapeUtils.escapeCsv(prices.getExistence())); sb.append("\n");
			*/

		}

		// FileUtils.writeStringToFile(tmpFile, sb.toString(), "utf-8");
		// pricesDao.saveBatch(tmpFile.getAbsolutePath());
		firePropertyChange("SAVE_DONE", false, pricesList.size());
		// tmpFile.delete();
		return savedRecords;
	}

	@Override
	protected void done() {
		super.done();
		logger.debug("SaveWorker done with: " + DurationFormatUtils.formatDuration((System.currentTimeMillis()-startTime), "s.S") + " sec");
		try {
			int savedResults = get();
			firePropertyChange("SAVE_OK", DurationFormatUtils.formatDuration((System.currentTimeMillis()-startTime), "s.S") + " sec", savedResults);
			pricesDao.getConn().commit();
			pricesDao.getConn().setAutoCommit(true);
			pricesFiles.setParsed(true);
			pricesFilesDao.update(pricesFiles);
		} catch (Exception e) {
			logger.error(e);
			firePropertyChange("SAVE_ERROR", null, e);
			try {
				pricesDao.getConn().rollback();
			} catch (SQLException e1) {
				logger.error(e);
			}
		}
	}

}
